#!/usr/bin/env python
# -*- coding:utf-8 -*-

# 200行Python代码实现2048
# http://www.cnblogs.com/mrchige/p/6389971.html
'''
curses 库 ( ncurses ) 提供了控制字符屏幕的独立于终端的方法。
curses 是大多数类似于 UNIX 的系统（包括 Linux）的标准部分，而且它已经移植到 Windows 和其它系统。
curses 程序将在纯文本系统上、xterm 和其它窗口化控制台会话中运行，这使这些应用程序具有良好的可移植性。
'''
# Redirection is not supported.
# 不支持重定向，那就试试在cmd控制台下执行。

import curses  # 引入curses模块，curses是一个在Linux/Unix下广泛应用的图形函数库.，作用是可以绘制在DOS下的用户界面和漂亮的图形。
from collections import defaultdict  # 从collections引入defaultdict这个类
from random import randrange, choice  # 从random模块引入randrange,choice这两个类

letter_codes = [ord(ch) for ch in 'WASDRQwasdrq']  # ord函数是把字符转换成对应的数字
actions = ['Up', 'Left', 'Down', 'Right', 'Restart', 'Exit']  # 上，左，下，右，重启，退出
actions_dict = dict(zip(letter_codes, actions * 2))  # 把字母与动作对应起来。 zip是把元组中的值对应起来。

'''
W或w      Up
A或a      Left
S或s      Down
D或d      Right
R或r      Restart
Q或q      Exit
'''


def get_user_action(keyboard):
    char = "N"  # char的初始值为N
    while char not in actions_dict:
        char = keyboard.getch()
    return actions_dict[char]  # 阻塞＋循环，直到获得用户有效输入才返回对应行为


def transpose(field):
    return [list(row) for row in
            zip(*field)]  # zip函数里边加*号，是把行变列，列变行。所以这句代码是行列转置


def invert(field):
    return [row[::-1] for row in field]  # 这句代码是把列表前后颠倒


class GameField(object):  # 创建一个叫做GameField的类，用来创建棋盘
    def __init__(self, height=4, width=4, win=2048):  # 这个类三个参数
        self.height = height  # 高
        self.width = width  # 宽
        self.win_value = win  # 过关分数
        self.score = 0  # 当前分数
        self.highscore = 0  # 最高分
        self.reset()  # 重置棋盘

    def reset(self):  # 定义一个reset函数
        if self.score > self.highscore:  # 如果当前分数大于最高分，那么把当前分数赋值给最高分
            self.highscore = self.score
        self.score = 0  # 当前分数恢复到0分
        self.field = [[0 for i in range(self.width)] for j in
                      range(self.height)]  # 横纵坐标恢复到（0,0）
        self.spawn()  # 调用spawn这个函数
        self.spawn()

    def move(self, direction):  # 定义move函数
        def move_row_left(row):  # 向左移
            def tighten(row):  # squeese non-zero elements together 把零散的非零单元挤到一块
                new_row = [i for i in row if i != 0]  # 如果i不等于零，把他们赋值到new_row这个元组中
                new_row += [0 for i in range(len(row) - len(new_row))]  # 其余位置用0补充
                return new_row  # 返回这个元组

            def merge(row):  # 定义merge函数，用来合并单元
                pair = False  # pair初始值为假
                new_row = []  # new_row初始值为空
                for i in range(len(row)):  # 让i在格子里循环
                    if pair:  # 如果pair为真
                        new_row.append(2 * row[i])  # 那么把把row【i】的值乘以2，追加到new_row后边
                        self.score += 2 * row[i]  # 并且得分为row【i】的值乘以2
                        pair = False  # pair重新赋值为假
                    else:
                        if i + 1 < len(row) and row[i] == row[i + 1]:  # 如果i+1还没到边界，并且此时的row【i】=row【i+1】
                            pair = True  # 那么pair为真
                            new_row.append(0)  # new_row后追加零
                        else:
                            new_row.append(row[i])  # 否则追加row【i】
                assert len(new_row) == len(row)  # 提醒两者长度一致
                return new_row

            return tighten(merge(tighten(row)))  # 反复合并，知道不能合并为止

        moves = {}
        moves['Left'] = lambda field: \
            [move_row_left(row) for row in field]  # 做移动
        moves['Right'] = lambda field: \
            invert(moves['Left'](invert(field)))  # invert是逆转
        moves['Up'] = lambda field: \
            transpose(moves['Left'](transpose(field)))  # transpose是转置
        moves['Down'] = lambda field: \
            transpose(moves['Right'](transpose(field)))

        if direction in moves:
            if self.move_is_possible(direction):  # 如果移动方向在四个方向上，
                self.field = moves[direction](self.field)
                # 那么调用moves函数
                self.spawn()  # 产生随机数
                return True
            else:
                return False

    def is_win(self):
        return any(any(i >= self.win_value for i in row) for row in self.field)

    def is_gameover(self):
        return not any(self.move_is_possible(move) for move in actions)

    def draw(self, screen):
        help_string1 = '(W)Up (S)Down (A)Left (D)Right'
        help_string2 = '     (R)Restart (Q)Exit'
        gameover_string = '           GAME OVER'
        win_string = '          YOU WIN!'

        def cast(string):
            screen.addstr(string + '\n')

        def draw_hor_separator():
            line = '+' + ('+------' * self.width + '+')[1:]
            separator = defaultdict(lambda: line)
            if not hasattr(draw_hor_separator, "counter"):
                draw_hor_separator.counter = 0
            cast(separator[draw_hor_separator.counter])
            draw_hor_separator.counter += 1

        def draw_row(row):
            cast(''.join('|{: ^5} '.format(num) if num > 0 else '|      ' for num in
                         row) + '|')

        screen.clear()
        cast('SCORE: ' + str(self.score))
        if 0 != self.highscore:
            cast('HGHSCORE: ' + str(self.highscore))
        for row in self.field:
            draw_hor_separator()
            draw_row(row)
        draw_hor_separator()
        if self.is_win():
            cast(win_string)
        else:
            if self.is_gameover():
                cast(gameover_string)
            else:
                cast(help_string1)
        cast(help_string2)

    def spawn(self):
        new_element = 4 if randrange(100) > 89 else 2
        (i, j) = choice(
            [(i, j) for i in range(self.width) for j in range(self.height) if
             self.field[i][j] == 0])
        self.field[i][j] = new_element

    def move_is_possible(self, direction):
        def row_is_left_movable(row):
            def change(i):  # true if there'll be change in i-th tile
                if row[i] == 0 and row[i + 1] != 0:  # Move
                    return True
                if row[i] != 0 and row[i + 1] == row[i]:  # Merge
                    return True
                return False

            return any(change(i) for i in range(len(row) - 1))

        check = {}
        check['Left'] = lambda field: \
            any(row_is_left_movable(row) for row in field)

        check['Right'] = lambda field: \
            check['Left'](invert(field))

        check['Up'] = lambda field: \
            check['Left'](transpose(field))

        check['Down'] = lambda field: \
            check['Right'](transpose(field))

        if direction in check:
            return check[direction](self.field)
        else:
            return False


def main(stdscr):
    def init():
        # 重置游戏棋盘
        game_field.reset()
        return 'Game'

    def not_game(state):
        # 画出 GameOver 或者 Win 的界面
        game_field.draw(stdscr)
        # 读取用户输入得到action，判断是重启游戏还是结束游戏
        action = get_user_action(stdscr)
        responses = defaultdict(lambda: state)  # 默认是当前状态，没有行为就会一直在当前界面循环
        responses['Restart'], responses[
            'Exit'] = 'Init', 'Exit'  # 对应不同的行为转换到不同的状态
        return responses[action]

    def game():
        # 画出当前棋盘状态
        game_field.draw(stdscr)
        # 读取用户输入得到action
        action = get_user_action(stdscr)

        if action == 'Restart':
            return 'Init'
        if action == 'Exit':
            return 'Exit'
        if game_field.move(action):  # move successful
            if game_field.is_win():
                return 'Win'
            if game_field.is_gameover():
                return 'Gameover'
        return 'Game'

    state_actions = {
        'Init': init,
        'Win': lambda: not_game('Win'),
        'Gameover': lambda: not_game('Gameover'),
        'Game': game
    }

    curses.use_default_colors()
    game_field = GameField(win=32)

    state = 'Init'

    # 状态机开始循环
    while state != 'Exit':
        state = state_actions[state]()


if __name__ == "__main__":
    curses.wrapper(main)

# Redirection is not supported.
# 不支持重定向，那就试试在cmd控制台下执行。
